import axios from 'axios';
// env
const apiUrl = import.meta.env.VITE_API_URL || 'https://localhost:5001';
const api = axios.create({
  baseURL: apiUrl,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) {
      // 未授权，清除 token 并跳转到登录页
      localStorage.removeItem('token');
      window.location.hash = '#/login';
    }
    return Promise.reject(error);
  }
);

// 用户相关 API
export const userApi = {
  // 登录
  login: (data) => api.post('/users/login', data),
  
  // 注册
  register: (data) => api.post('/users/register', data),
  
  // 获取所有用户
  getAllUsers: () => api.get('/users'),
  
  // 创建用户
  createUser: (data) => api.post('/users', data),
  
  // 更新用户
  updateUser: (id, data) => api.put(`/users/${id}`, data),
  
  // 删除用户
  deleteUser: (id) => api.delete(`/users/${id}`)
};

// 设备相关 API
export const deviceApi = {
  // 获取所有设备
  getAllDevices: () => api.get('/devices'),
  
  // 获取用户设备
  getUserDevices: (userId) => api.get(`/devices/user/${userId}`),
  
  // 创建设备
  createDevice: (data) => api.post('/devices', data),
  
  // 更新设备
  updateDevice: (id, data) => api.put(`/devices/${id}`, data),
  
  // 删除设备
  deleteDevice: (id) => api.delete(`/devices/${id}`),

  // 获取设备属性
  getDeviceProperties: async (deviceId) => {
    const response = await api.get(`/devices/properties/${deviceId}`);
    return response.data;
  },

  // 获取设备消息流
  getDeviceStream: (deviceId) => {
    const token = localStorage.getItem('token');
    const eventSource = new EventSource(`${apiUrl}/devices/stream/${deviceId}?token=${token}`);
    return eventSource;
  },

  executeCommand: (deviceId, command) => {
    return api.post(`/devices/${deviceId}/command`, { key: command.key, value: command.value});
  },
  
  // 更新设备属性
  updateDeviceProperty: (deviceId, property) => {
    return api.post(`/devices/${deviceId}/command`, { key: property.key, value: property.value});
  }
};

export default api;